package com.mybatis.plug.slicingStrategy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class StrategyManager {
    private static final Logger logger = LoggerFactory.getLogger(StrategyManager.class);

    //分表策略
    private Map<String, Strategy> strategies = new ConcurrentHashMap<String, Strategy>(10);
    //需要分表的表
    private Map<String, String> slicingTables = new ConcurrentHashMap<String, String>(10);

    public Strategy getStrategy(String key) {
        return strategies.get(key);
    }

    public Class<?> getSlicingTablesEntity(String key) throws Exception {
        return Class.forName(slicingTables.get(key.toUpperCase()));
    }

    public boolean isSlicingTables(String tableName) {
        //key强制大写
        return slicingTables.containsKey(tableName.toUpperCase());
    }

    public Map<String, Strategy> getStrategies() {
        return strategies;
    }

    public void setStrategies(Map<String, String> strategies) {
        for (Map.Entry<String, String> entry : strategies.entrySet()) {
            try {
                this.strategies.put(entry.getKey(), (Strategy) Class.forName(entry.getValue()).newInstance());
            } catch (Exception e) {
                logger.error("获取分表策略异常" + e.getMessage(), e);
            }
        }
    }

    public void setSlicingTables(Map<String, String> slicingTables) {
        for (Map.Entry<String, String> entry : slicingTables.entrySet()) {
            try {
                this.slicingTables.put(entry.getKey().toUpperCase(), entry.getValue());
            } catch (Exception e) {
                logger.error("获取分表数据集合异常" + e.getMessage(), e);
            }
        }
    }
}